package com.example.demo.utils;

import com.example.demo.identity.User;
import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@Data
public class ResponseMessage {


    public String message;

    private HttpStatus status;

    public ResponseEntity<Map<String, Object>> responseMessage(String message, HttpStatus status) {
        Map<String, Object> data = createData(message, status);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", data);

        return ResponseEntity.status(status).body(resultMap);
    }

    public ResponseEntity<Map<String, Object>> responseMessage(String message, HttpStatus status, User user) {
        Map<String, Object> data = createData(message, status, "user", user, "token");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", data);

        return ResponseEntity.status(status).body(resultMap);
    }

    public ResponseEntity<Map<String, Object>> responseMessage(String message, HttpStatus status, User user, String token) {
        Map<String, Object> data = createData(message, status, "user", user, "token", token);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", data);

        return ResponseEntity.status(status).body(resultMap);
    }

    /**
     * 通用方法，用于生成包含 message 和 status 的 data 字段
     */
//    additionalFields 传递参数的时候要以键值对的形式传入
    public Map<String, Object> createData(String message, HttpStatus status, Object... additionalFields) {
        Map<String, Object> data = new HashMap<>();
        data.put("message", message);
        data.put("status", status); // 使用 status.value() 获取状态码的整数值

//        如果有额外的字段，添加到data中
        for (int i = 0; i < additionalFields.length; i += 2) {
            if (i + 1 < additionalFields.length) {
                data.put((String) additionalFields[i], additionalFields[i + 1]);
            }
        }
        return data;
    }
}
